package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.dto.QuestionCreateDTO;
import com.zenithmind.exam.pojo.entity.Question;
import com.zenithmind.exam.pojo.vo.QuestionVO;
import com.zenithmind.exam.service.QuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 题目控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/question")
@RequiredArgsConstructor
@Validated
@Tag(name = "题目管理", description = "题目的增删改查操作")
public class QuestionController {

    private final QuestionService questionService;

    @PostMapping
    @Operation(summary = "创建题目", description = "创建新的题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> createQuestion(@Valid @RequestBody QuestionCreateDTO questionCreateDTO) {
        boolean result = questionService.createQuestion(questionCreateDTO);
        return Result.success(result);
    }

    @PutMapping("/{questionId}")
    @Operation(summary = "更新题目", description = "更新指定的题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateQuestion(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Valid @RequestBody QuestionCreateDTO questionCreateDTO) {
        boolean result = questionService.updateQuestion(questionId, questionCreateDTO);
        return Result.success(result);
    }

    @DeleteMapping("/{questionId}")
    @Operation(summary = "删除题目", description = "删除指定的题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> deleteQuestion(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        boolean result = questionService.deleteQuestion(questionId);
        return Result.success(result);
    }

    @GetMapping("/{questionId}")
    @Operation(summary = "获取题目详情", description = "根据ID获取题目详情")
    public Result<QuestionVO> getQuestionById(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Parameter(description = "是否显示答案") @RequestParam(defaultValue = "false") Boolean showAnswer) {
        QuestionVO question = questionService.getQuestionById(questionId, showAnswer);
        return Result.success(question);
    }

    @GetMapping("/bank/{bankId}")
    @Operation(summary = "获取题库题目列表", description = "根据题库ID获取题目列表")
    public Result<List<QuestionVO>> getQuestionsByBankId(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        List<QuestionVO> questions = questionService.getQuestionsByBankId(bankId);
        return Result.success(questions);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询题目", description = "分页查询题目列表")
    public Result<IPage<QuestionVO>> getQuestionPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "题库ID") @RequestParam(required = false) String bankId,
            @Parameter(description = "题目标题") @RequestParam(required = false) String title,
            @Parameter(description = "题目类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "难度等级") @RequestParam(required = false) Integer difficulty,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        
        Page<Question> page = new Page<>(pageNum, pageSize);
        IPage<QuestionVO> result = questionService.getQuestionPage(page, bankId, title, type, difficulty, status);
        return Result.success(result);
    }

    @GetMapping("/random")
    @Operation(summary = "随机获取题目", description = "随机获取指定条件的题目")
    public Result<List<QuestionVO>> getRandomQuestions(
            @Parameter(description = "题库ID") @RequestParam(required = false) String bankId,
            @Parameter(description = "题目类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "难度等级") @RequestParam(required = false) Integer difficulty,
            @Parameter(description = "数量") @RequestParam(defaultValue = "10") Integer count) {
        List<QuestionVO> questions = questionService.getRandomQuestions(bankId, type, difficulty, count);
        return Result.success(questions);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索题目", description = "根据关键词搜索题目")
    public Result<List<QuestionVO>> searchQuestions(
            @Parameter(description = "搜索关键词") @RequestParam @NotBlank String keyword) {
        List<QuestionVO> questions = questionService.searchQuestions(keyword);
        return Result.success(questions);
    }

    @GetMapping("/tag/{tag}")
    @Operation(summary = "根据标签获取题目", description = "根据标签获取题目列表")
    public Result<List<QuestionVO>> getQuestionsByTag(
            @Parameter(description = "标签") @PathVariable @NotBlank String tag) {
        List<QuestionVO> questions = questionService.getQuestionsByTag(tag);
        return Result.success(questions);
    }

    @PutMapping("/{questionId}/status")
    @Operation(summary = "更新题目状态", description = "启用或禁用题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateQuestionStatus(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        boolean result = questionService.updateQuestionStatus(questionId, status);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除题目", description = "批量删除指定的题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchDeleteQuestions(
            @Parameter(description = "题目ID列表") @RequestBody List<String> questionIds) {
        boolean result = questionService.batchDeleteQuestions(questionIds);
        return Result.success(result);
    }

    @PostMapping("/{questionId}/copy")
    @Operation(summary = "复制题目", description = "复制题目到其他题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> copyQuestionToBank(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Parameter(description = "目标题库ID") @RequestParam @NotBlank String targetBankId) {
        boolean result = questionService.copyQuestionToBank(questionId, targetBankId);
        return Result.success(result);
    }

    @PostMapping("/{questionId}/move")
    @Operation(summary = "移动题目", description = "移动题目到其他题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> moveQuestionToBank(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Parameter(description = "目标题库ID") @RequestParam @NotBlank String targetBankId) {
        boolean result = questionService.moveQuestionToBank(questionId, targetBankId);
        return Result.success(result);
    }

    @GetMapping("/frequent-wrong")
    @Operation(summary = "获取高频错题", description = "获取高频错题列表")
    public Result<List<QuestionVO>> getFrequentWrongQuestions(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<QuestionVO> questions = questionService.getFrequentWrongQuestions(limit);
        return Result.success(questions);
    }

    @PostMapping("/import/{bankId}")
    @Operation(summary = "导入题目", description = "批量导入题目到指定题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> importQuestions(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId,
            @Parameter(description = "题目列表") @RequestBody @Valid List<QuestionCreateDTO> questions) {
        boolean result = questionService.importQuestions(bankId, questions);
        return Result.success(result);
    }

    @GetMapping("/export/{bankId}")
    @Operation(summary = "导出题目", description = "导出指定题库的所有题目")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> exportQuestions(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        List<QuestionVO> questions = questionService.exportQuestions(bankId);
        return Result.success(questions);
    }
}
